/**
 * API配置和HTTP客户端封装
 */

import { API_CONFIG } from '../config/environment';

// Re-export API_CONFIG for other services to use
export { API_CONFIG };

// API响应基础类型
export interface ApiResponse<T = any> {
  code: number;
  msg: string;
  data: T;
}

// 分页响应类型
export interface PageResponse<T = any> {
  records: T[];
  total: number;
  size: number;
  current: number;
  pages: number;
}

// 表格分页数据类型
export interface TableDataInfo<T = any> {
  total: number;
  rows: T[];
  code: number;
  msg: string;
}

// HTTP请求方法类型
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';

// 请求配置类型
export interface RequestConfig {
  url: string;
  method: HttpMethod;
  data?: any;
  params?: Record<string, any>;
  headers?: Record<string, string>;
  timeout?: number;
}

import { Storage } from './storage';

// 认证token管理
class AuthManager {
  private static TOKEN_KEY = 'auth_token';
  private static cachedToken: string | null = null;

  static async getToken(): Promise<string | null> {
    try {
      if (this.cachedToken) {
        return this.cachedToken;
      }

      const token = await Storage.getItem(this.TOKEN_KEY);
      this.cachedToken = token;
      return token;
    } catch (error) {
      console.error('获取token失败:', error);
      return null;
    }
  }

  static async setToken(token: string): Promise<void> {
    try {
      await Storage.setItem(this.TOKEN_KEY, token);
      this.cachedToken = token;
    } catch (error) {
      console.error('保存token失败:', error);
      throw error;
    }
  }

  static async removeToken(): Promise<void> {
    try {
      await Storage.removeItem(this.TOKEN_KEY);
      this.cachedToken = null;
    } catch (error) {
      console.error('刪除token失敗:', error);
      throw error;
    }
  }

  static async isAuthenticated(): Promise<boolean> {
    const token = await this.getToken();
    return !!token;
  }

  // 同步方法（用于兼容现有代码）
  static getTokenSync(): string | null {
    return this.cachedToken;
  }
}

// HTTP客户端类
class HttpClient {
  private baseURL: string;
  private timeout: number;
  private defaultHeaders: Record<string, string>;

  constructor() {
    this.baseURL = API_CONFIG.BASE_URL;
    this.timeout = API_CONFIG.TIMEOUT;
    this.defaultHeaders = { ...API_CONFIG.HEADERS };
  }

  private async request<T = any>(config: RequestConfig): Promise<ApiResponse<T>> {
    const { url, method, data, params, headers = {}, timeout = this.timeout } = config;

    // 构建完整URL
    let fullUrl = `${this.baseURL}${url}`;
    
    // 添加查询参数
    if (params && Object.keys(params).length > 0) {
      const searchParams = new URLSearchParams();
      Object.entries(params).forEach(([key, value]) => {
        if (value !== undefined && value !== null) {
          searchParams.append(key, String(value));
        }
      });
      fullUrl += `?${searchParams.toString()}`;
    }

    // 合并headers
    const mergedHeaders = {
      ...this.defaultHeaders,
      ...headers,
    };

    // 添加认证token
    const token = AuthManager.getTokenSync() || await AuthManager.getToken();
    if (token) {
      mergedHeaders.Authorization = `Bearer ${token}`;
    }

    try {
      console.log('🌐 发送网络请求:', {
        url: fullUrl,
        method,
        headers: mergedHeaders,
        hasBody: !!data,
        data: data,
        bodyContent: data ? JSON.stringify(data) : 'no body'
      });

      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), timeout);

      const response = await fetch(fullUrl, {
        method,
        headers: mergedHeaders,
        body: data ? JSON.stringify(data) : undefined,
        signal: controller.signal,
      });

      clearTimeout(timeoutId);

      console.log('📡 网络响应:', {
        status: response.status,
        statusText: response.statusText,
        ok: response.ok,
        url: response.url
      });

      if (!response.ok) {
        const errorText = await response.text();
        console.error('❌ API响应错误:', {
          status: response.status,
          statusText: response.statusText,
          errorText,
          url: fullUrl
        });
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const result = await response.json();
      console.log('✅ API响应成功:', { url: fullUrl, result: result });
      return result as ApiResponse<T>;
    } catch (error) {
      console.error('💥 API请求失败:', {
        error: error instanceof Error ? error.message : String(error),
        url: fullUrl,
        method,
        type: error instanceof Error ? error.name : 'Unknown'
      });
      throw error;
    }
  }

  async get<T = any>(url: string, params?: Record<string, any>, headers?: Record<string, string>): Promise<ApiResponse<T>> {
    return this.request<T>({ url, method: 'GET', params, headers });
  }

  async post<T = any>(url: string, data?: any, headers?: Record<string, string>): Promise<ApiResponse<T>> {
    return this.request<T>({ url, method: 'POST', data, headers });
  }

  async put<T = any>(url: string, data?: any, headers?: Record<string, string>): Promise<ApiResponse<T>> {
    return this.request<T>({ url, method: 'PUT', data, headers });
  }

  async delete<T = any>(url: string, params?: Record<string, any>, headers?: Record<string, string>): Promise<ApiResponse<T>> {
    return this.request<T>({ url, method: 'DELETE', params, headers });
  }
}

// 导出单例实例
export const httpClient = new HttpClient();
export { AuthManager };

// API基础服务类
export abstract class BaseApiService {
  protected http = httpClient;

  protected handleError(error: any): never {
    console.error('API服务错误:', error);
    throw error;
  }

  protected async handleResponse<T>(promise: Promise<ApiResponse<T>>): Promise<T> {
    try {
      const response = await promise;
      console.log('🔍 處理響應:', response);

      // 检查是否是标准的ApiResponse格式 {code: number, msg: string, data: T}
      if (response.code !== undefined) {
        console.log('📋 標準API響應格式');
        if (response.code === 200) {
          return response.data;
        } else {
          throw new Error(response.msg || '請求失敗');
        }
      }

      // 检查是否是HTTP Response对象格式 {ok: boolean, status: number, ...}
      if ((response as any).ok !== undefined) {
        const httpResponse = response as any;
        console.log('🌐 HTTP響應格式:', httpResponse);
        if (httpResponse.ok && httpResponse.status === 200) {
          // 对于添加课程等操作，如果成功就返回true
          console.log('✅ HTTP響應成功，返回true');
          return true as T;
        } else {
          throw new Error(httpResponse.statusText || '請求失敗');
        }
      }

      // 检查是否直接是数据（某些API可能直接返回数据）
      if (typeof response === 'object' && response !== null) {
        console.log('📦 直接數據響應');
        return response as T;
      }

      // 如果都不匹配，抛出错误
      console.error('❌ 未知響應格式:', response);
      throw new Error('響應格式不正確');
    } catch (error) {
      console.error('💥 handleResponse錯誤:', error);
      this.handleError(error);
    }
  }
}
